<?php
namespace common\libraries\collector;

class Collector{

    /**
     * 支持HTTPS的CURL请求
     * @param $url
     * @param $params
     * @param int $timeout
     * @return mixed
     */
    public static function httpscurl($url, $params = [], $cookies = '', $timeout = 30){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//SSL证书认证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//严格认证
        curl_setopt($ch, CURLOPT_HEADER, 0 ); // 过滤HTTP头
        $agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
        curl_setopt($ch, CURLOPT_USERAGENT, $agent);//如果有些页面返回403，把这个加上就好了
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果

        curl_setopt ($ch, CURLOPT_COOKIE , $cookies );
        curl_setopt($ch,CURLOPT_POST,true); // post传输数据
        curl_setopt($ch,CURLOPT_POSTFIELDS, $params);// post传输数据
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $responseText = curl_exec($ch);
        curl_close($ch);
        return $responseText;
    }

    /**
     * POST形式的file_get_contents 相当于POSTMAN 里的 BODY下x-www-form-urlencoded方式请求
     * 此方法对调用SERVLET效果非常好，都是UTF-8的时候不用转编码，而且不需要URLENCODE了
     * @param $url
     * @param $params
     * @return bool|string
     */
    public static function file_get_contents_post($url, $params){
        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => http_build_query($params),
                'timeout' => 20
            ]
        ]);
        return file_get_contents($url, false, $context);
    }

    /**
     * 保存网络文件到硬盘
     * @param $urlFile
     * @param $saveFile
     * @return bool
     */
    public static function saveUrlFile($urlFile, $saveFile){

        if(empty($urlFile)){
            throw new \RuntimeException("文件路径不存在");
            return false;
        }

        //资源判断
        $img = file_get_contents($urlFile);
        if(empty($img)){
            throw new \RuntimeException("得不到网络资源");
            return false;
        }

        //判断目录
        $saveDir = dirname($saveFile);
        if(!file_exists($saveDir)){
            throw new \RuntimeException("目录不存在");
            return false;
        }

        //判断目录是否可写
        if(!is_writable($saveDir)){
            throw new \RuntimeException("目录不可写");
            return false;
        }

        //保存文件
        if(!file_put_contents($saveFile, $img)){
            throw new \RuntimeException("文件保存失败");
            return false;
        }

        return true;
    }

    /**
     * 过滤HTML标签、换行、TAB、空格等，得到纯文本
     * @param $text
     * @return null|string|string[]
     */
    public static function pureness($text){
        $text = strip_tags($text);
        $text = preg_replace('/[\s]/', '', $text);
        $text = preg_replace('#　#', '', $text);
        return $text;
    }

}
